import React from 'react';
import { Balloon, DatePicker, Select } from '@teamix/ui';
import { ButtonIcon, YunxiaoIcon } from '@alife/devops-ui';
import Wcontainer from '@alife/aisc-widgets/lib/Wcontainer';
import Wline from '@alife/aisc-widgets/lib/Wline';
import Wbar from '@alife/aisc-widgets/lib/Wbar';
import ListLoading from 'atComponents/ListLoading';
import dayjs from 'dayjs';
import track from 'utils/track';
import exceed from 'utils/apimap';
import docs from 'utils/docs';
import intl from '../../../../../../../locale';

const { pathResource } = window.FORCE;
const prefix = 'project-statistics-commit';
const dimensions = [
  {
    value: 'commit',
    label: intl.get({
      id: 'code-assets.projectInsight.containers.commitInfo.Submitted',
      defaultMessage: '提交',
    }),
  },

  {
    value: 'line',
    label: intl.get({
      id: 'code-assets.projectInsight.containers.commitInfo.CodeQuantity',
      defaultMessage: '代码量',
    }),
  },
];

const addColor = '#65cd9a';
const deleteColor = '#ee8b85';
// eslint-disable-next-line no-unused-vars
const widgetsColorCategory2 = '#5ccdbb'; // FIXME: 为图表库按需加载，原为 COLORS.widgetsColorCategory2

export default class CommitInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rangeTmp: [props.commit_start_time, props.commit_end_time],
      branches: [
        intl.get({
          id: 'code-assets.projectInsight.containers.commitInfo.All',
          defaultMessage: '全部',
        }),
      ],
    };
  }

  componentDidMount() {
    this.fetchBranches();
    this.props.updateStatisticsData({
      commit_branch: intl.get({
        id: 'code-assets.projectInsight.containers.commitInfo.All',
        defaultMessage: '全部',
      }),
    });

    const { isMock } = this.props;
    if (!isMock) {
      this.props.getTotalCommitData();
      this.props.getDetailCommitData();
    }
  }

  fetchBranches = () => {
    exceed
      .fetch({
        api: 'projects.all.branches.search',
        params: {
          id: pathResource.id,
        },
      })
      .then((result) => {
        result.unshift({
          name: intl.get({
            id: 'code-assets.projectInsight.containers.commitInfo.All',
            defaultMessage: '全部',
          }),
          value: null,
        });
        this.setState({
          branches: result.filter((v) => v.name),
        });
      });
  };

  toggleDimension = (value) => {
    track({
      action: value === 'commit' ? 'check_commits' : 'check_code',
      page: 'Charts Page',
      type: '',
      control: '',
    });

    this.props.updateStatisticsData({
      commit_dimension: value,
    });
  };

  toggleBranch = (value) => {
    track({
      action: 'switch_branch',
      page: 'Charts Page',
      type: '',
      control: '',
    });

    this.props.updateStatisticsData({
      commit_branch: value,
    });

    const { isMock } = this.props;
    if (!isMock) {
      this.props.getTotalCommitData();
      this.props.getDetailCommitData();
    }
  };

  onRangePickerOk = (range) => {
    if (!range || !range.length) {
      return;
    }
    this.props.updateStatisticsData({
      commit_start_time: range[0],
      commit_end_time: range[1],
    });

    const { isMock } = this.props;
    if (!isMock) {
      this.props.getTotalCommitData();
      this.props.getDetailCommitData();
    }
  };

  getDateArr = (start, end) => {
    const arr = [start];
    let temp = start;
    while (dayjs(temp).isBefore(dayjs(end))) {
      temp = dayjs(temp).add(1, 'day').format('YYYY-MM-DD');
      arr.push(temp);
    }
    return arr;
  };

  getDetailInfo = (daily_detail, key) => {
    if (!daily_detail) {
      return [];
    }
    // 将每天的数据都显示出来，没有就填0
    const { commit_start_time, commit_end_time } = this.props;
    const dateArr = this.getDateArr(commit_start_time, commit_end_time);

    // 接口返回修改没有按照日期聚合，前端按日期聚合
    const new_daily_detail = [];
    if (daily_detail) {
      daily_detail.forEach((d) => {
        const curDateData = new_daily_detail.find((new_d) => {
          return new_d.date === d.date;
        });
        if (curDateData) {
          curDateData.add_line_count += d.add_line_count || 0;
          curDateData.del_line_count += d.del_line_count || 0;
          curDateData.commits_count += d.commits_count || 0;
        } else {
          new_daily_detail.push({
            ...d,
          });
        }
      });
    }

    return dateArr.map((date) => {
      const daily_detail_info = new_daily_detail.find((item) => {
        return dayjs(item.date).format('YYYY-MM-DD') === date;
      });
      return [date, daily_detail_info ? daily_detail_info[key] : 0];
    });
  };

  disabledDate = (date) => {
    const { rangeTmp } = this.state;
    let yearLimit = false;
    // 区间限制5年和当前日期以前
    if (rangeTmp && rangeTmp.length > 1) {
      const [start, end] = rangeTmp;
      yearLimit =
        (end && date.valueOf() < dayjs(end).subtract(1, 'year').valueOf()) ||
        (start && date.valueOf() > dayjs(start).add(1, 'year').valueOf());
    }
    return date.valueOf() > dayjs().valueOf() || yearLimit;
  };

  render() {
    const {
      commit_dimension,
      commit_branch,
      commit_start_time,
      commit_end_time,
      total_commit,
      detail_commit,
      isLoadingCommit,
    } = this.props;
    const { branches } = this.state;
    if (isLoadingCommit || !total_commit) {
      return <ListLoading className="project-content-loading" />;
    }

    const totalData = [
      {
        name: intl.get({
          id: 'code-assets.projectInsight.containers.commitInfo.NumberOfNewCommits',
          defaultMessage: '新增 Commits 数',
        }),
        data: this.getDetailInfo(total_commit.daily_detail, 'commits_count'),
      },
    ];

    const lineTotalData = [
      {
        name: intl.get({
          id: 'code-assets.projectInsight.containers.commitInfo.AddCodeLines',
          defaultMessage: '新增代码行',
        }),
        facet: intl.get({
          id: 'code-assets.projectInsight.containers.commitInfo.Add',
          defaultMessage: '新增',
        }),
        data: this.getDetailInfo(total_commit.daily_detail, 'add_line_count'),
      },

      {
        name: intl.get({
          id: 'code-assets.projectInsight.containers.commitInfo.DeleteALineOfCode',
          defaultMessage: '删除代码行',
        }),
        facet: intl.get({
          id: 'code-assets.projectInsight.containers.commitInfo.Delete',
          defaultMessage: '删除',
        }),
        data: this.getDetailInfo(total_commit.daily_detail, 'del_line_count'),
      },
    ];

    const isCommit = commit_dimension === 'commit';
    return (
      <div className={`${prefix}`}>
        <div className={`${prefix}-header`}>
          <div className={`${prefix}-header-left`}>
            <div style={{ marginRight: '12px' }}>
              <span className={`${prefix}-header-label`}>
                {intl.get({
                  id: 'code-assets.projectInsight.containers.commitInfo.Branch',
                  defaultMessage: '分支',
                })}
              </span>
              <Select onChange={this.toggleBranch} value={commit_branch}>
                {branches.map((item) => {
                  return (
                    <Select.Option key={item.name} value={item.name}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </div>
            <div style={{ marginRight: '12px' }}>
              <span className={`${prefix}-header-label`}>
                {intl.get({
                  id: 'code-assets.projectInsight.containers.commitInfo.Dimension',
                  defaultMessage: '维度',
                })}
              </span>
              <Select onChange={this.toggleDimension} value={commit_dimension}>
                {dimensions.map((item) => {
                  return (
                    <Select.Option key={item.value} value={item.value}>
                      {item.label}
                    </Select.Option>
                  );
                })}
              </Select>
            </div>
            <div>
              <span className={`${prefix}-header-label`}>时间范围</span>
              <DatePicker.RangePicker
                followTrigger
                popupAlign="tr br"
                onOk={this.onRangePickerOk}
                format="YYYY-MM-DD"
                defaultValue={[commit_start_time, commit_end_time]}
                disabledDate={this.disabledDate}
                onChange={(range) => {
                  this.setState({
                    rangeTmp: range,
                  });
                }}
              />
            </div>
          </div>
        </div>
        <section className={`${prefix}-overview project-statistics-card`}>
          <div className={`${prefix}-overview-title`}>
            <span>
              {intl.get({
                id: 'code-assets.projectInsight.containers.commitInfo.Overall',
                defaultMessage: '总体',
              })}
            </span>
            <Balloon.Tooltip
              popupStyle={{
                maxWidth: 450,
              }}
              trigger={
                <ButtonIcon
                  name="question-line"
                  style={{ marginLeft: 4, display: 'inline-block' }}
                />
              }
              align="r"
            >
              <div className="balloon-info-help">
                {isCommit ? (
                  <div className="balloon-info-help-desc">
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.commitInfo.ThisReportReflectsTheFrequency',
                      defaultMessage: '该报表反映了代码提交频率，最多统计 6000 个提交。',
                    })}

                    <br />
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.commitInfo.TheOverallReportShowsThe',
                      defaultMessage:
                        '总体报表展示了每天代码库中的提交总次数，各贡献者的报表展示了该用户每天的提交次数。',
                    })}

                    <br />
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.commitInfo.TheAboveDataCanHelp',
                      defaultMessage:
                        '以上数据可以帮助你了解当前代码库的研发活跃度，人员贡献情况。',
                    })}
                  </div>
                ) : (
                  <div className="balloon-info-help-desc">
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.commitInfo.ThisReportReflectsTheNumber',
                      defaultMessage: '该报表反映了新增和删除代码情况，最多统计 6000 个提交。',
                    })}

                    <br />
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.commitInfo.TheOverallReportDisplaysThe',
                      defaultMessage:
                        '总体报表展示了每天代码库中新增和删除的代码总量，各贡献者报表中展示了该用户每天的代码贡献量。',
                    })}

                    <br />
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.commitInfo.TheAboveDataCanHelp',
                      defaultMessage:
                        '以上数据可以帮助你了解当前代码库的研发活跃度，人员贡献情况。',
                    })}
                  </div>
                )}
              </div>
            </Balloon.Tooltip>
          </div>
          <div className={`${prefix}-overview-desc`}>
            {isCommit ? (
              intl.get(
                {
                  id: 'code-assets.projectInsight.containers.commitInfo.SubmittedTimesTotalcommitcommits',
                  defaultMessage: '提交次数 {totalCommitCommits}',
                },
                { totalCommitCommits: total_commit.commits_count_total },
              )
            ) : (
              <span>
                <span className="add">{total_commit.add_line_count_total} ++</span>
                <span className="delete">{total_commit.del_line_count_total} --</span>
              </span>
            )}
          </div>
          <div className={`${prefix}-overview-chart`}>
            <Wcontainer>
              {isCommit ? (
                <Wline
                  height="200"
                  config={{
                    area: true,
                    symbol: true,
                    legend: false,
                    xAxis: {
                      type: 'time',
                      mask: 'YYYY-MM-DD',
                    },

                    colors: ['#64baf7'],
                    padding: [32, 45, 32, 45],
                  }}
                  data={totalData}
                />
              ) : (
                <Wbar
                  height="240"
                  config={{
                    stack: true,
                    legend: {
                      visible: false,
                    },

                    xAxis: {
                      type: 'timeCat',
                      mask: 'YYYY-MM-DD',
                    },

                    colors: [addColor, deleteColor],
                    autoSort: false,
                    padding: [32, 45, 32, 45],
                    marginRatio: 0.05,
                    facet: true,
                  }}
                  data={lineTotalData}
                />
              )}
            </Wcontainer>
          </div>
        </section>
        <section className={`${prefix}-list`}>
          {detail_commit &&
            detail_commit.map((item, index) => {
              const { user_info, rank, personal_commit_report } = item;
              const itemCommits = [
                {
                  name: intl.get({
                    id: 'code-assets.projectInsight.containers.commitInfo.SubmittedTimes',
                    defaultMessage: '提交次数',
                  }),
                  data: this.getDetailInfo(personal_commit_report.daily_detail, 'commits_count'),
                },
              ];

              const itemLines = [
                {
                  name: intl.get({
                    id: 'code-assets.projectInsight.containers.commitInfo.AddCodeLines',
                    defaultMessage: '新增代码行',
                  }),
                  facet: intl.get({
                    id: 'code-assets.projectInsight.containers.commitInfo.Add',
                    defaultMessage: '新增',
                  }),
                  data: this.getDetailInfo(personal_commit_report.daily_detail, 'add_line_count'),
                },

                {
                  name: intl.get({
                    id: 'code-assets.projectInsight.containers.commitInfo.DeleteALineOfCode',
                    defaultMessage: '删除代码行',
                  }),
                  facet: intl.get({
                    id: 'code-assets.projectInsight.containers.commitInfo.Delete',
                    defaultMessage: '删除',
                  }),
                  data: this.getDetailInfo(personal_commit_report.daily_detail, 'del_line_count'),
                },
              ];

              if (user_info.name === 'unknown') {
                user_info.username = 'unknown';
                user_info.name = (
                  <div>
                    {intl.get({
                      id: 'code-assets.projectInsight.containers.commitInfo.UnknownNotMatchingEnterpriseMembers',
                      defaultMessage: '未知（未匹配企业成员）',
                    })}
                    <Balloon.Tooltip align="t" trigger={<YunxiaoIcon type="question-line" />}>
                      {intl.get({
                        id: 'code-assets.projectInsight.containers.commitInfo.TheSubmittedEmailAddressDoes',
                        defaultMessage: '提交邮箱（email）未匹配任何企业成员主邮箱',
                      })}
                      <a href={docs('howCanCodeContributionsBe')} target="_blank" rel="noreferrer">
                        {intl.get({
                          id: 'code-assets.projectInsight.containers.commitInfo.HowDoISetThis',
                          defaultMessage: '如何设置才能被统计？',
                        })}
                      </a>
                    </Balloon.Tooltip>
                  </div>
                );
              }
              return (
                <div className={`${prefix}-list-item project-statistics-card`}>
                  <div className="user-info">
                    <div className="user-info-left">
                      <div className={`avatar ${index === 0 ? 'active' : ''}`}>
                        {user_info.username !== 'unknown' ? (
                          <img src={user_info.avatar_url} alt="" width="40" height="40" />
                        ) : (
                          <div className="avatar-known">
                            {intl.get({
                              id: 'code-assets.projectInsight.containers.commitInfo.Not',
                              defaultMessage: '未',
                            })}
                          </div>
                        )}
                      </div>
                      <div>
                        <div className="user">{user_info.name}</div>
                        {isCommit ? (
                          <div className="desc">
                            {intl.get({
                              id: 'code-assets.projectInsight.containers.commitInfo.SubmittedTimes',
                              defaultMessage: '提交次数',
                            })}
                            {personal_commit_report.commits_count_total}
                          </div>
                        ) : (
                          <div>
                            <span className="add">
                              {personal_commit_report.add_line_count_total} ++
                            </span>
                            <span className="delete">
                              {personal_commit_report.del_line_count_total} --
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                    {rank ? <div className="user-info-right">{`#${rank}`}</div> : null}
                  </div>
                  <div className="chart">
                    <Wcontainer>
                      {isCommit ? (
                        <Wline
                          height="120"
                          config={{
                            legend: {
                              visible: false,
                            },

                            xAxis: {
                              type: 'time',
                              mask: 'YYYY-MM-DD',
                            },

                            area: true,
                            symbol: true,
                            colors: user_info.username === 'unknown' ? ['#dbdbdb'] : ['#64baf7'],
                          }}
                          data={itemCommits}
                        />
                      ) : (
                        <Wbar
                          height="240"
                          config={{
                            stack: true,
                            legend: {
                              visible: false,
                            },

                            xAxis: {
                              type: 'timeCat',
                              mask: 'YYYY-MM-DD',
                            },

                            padding: [32, 30, 32, 45],
                            colors: [addColor, deleteColor],
                            autoSort: false,
                            marginRatio: 0.05,
                            facet: true,
                          }}
                          data={itemLines}
                        />
                      )}
                    </Wcontainer>
                  </div>
                </div>
              );
            })}
        </section>
      </div>
    );
  }
}
